<?php
/**
 * Created by LíJimpéy(：
 * User: jimpey88
 * Date: 2024/04/09
 * Email: < jimpey@qq.com >
 * Project: company-admin-tp6
 */
declare (strict_types = 1);

namespace app\backend_api\controller;

use app\backend_api\model\Articles;
use app\backend_api\model\Sorts;
use app\backend_api\validate\ArticleValidate;
use app\BaseController;
use app\common\Utils\IpInfoUtils;
use think\db\exception\DbException;
use think\facade\Db;

class Article extends BaseController
{
    public function sortList()
    {
        $data = Sorts::column('name');
        array_walk($data, function(&$value) {
            $value = ['value' => $value];
        });

        return $this->success($data);
    }

    /**
     * @throws DbException
     */
    public function articleList()
    {
        $page = (int)input('currentPage', 1);
        $pageSize = (int)input('pageSize', 4);
        $query = Articles::order('id', 'desc')->append(['sort_name'])
            ->paginate(['page' => $page, 'list_rows' => $pageSize]);

        $data = [
            'current_page' => $query->currentPage(),
            'per_page' => $pageSize,
            'count_page' => $query->lastPage(),
            'total' => $query->total(),
            'data' => $query->items(),
        ];
        return $this->success($data);
    }

    public function create(ArticleValidate $articleValidate)
    {
        // 参数检验
        $editId = input('articleId', 0);
        if ($editId) {
            $params = $articleValidate->post()->goCheck('edit');
        } else {
            $params = $articleValidate->post()->goCheck('create');
        }

        $postData = array_intersect_key($params, array_flip(['title','sort_name','thumbnail','banner','is_top','content']));
//        dd($postData);

        Db::startTrans();
        try {
            $existSortId = Sorts::where('name', $postData['sort_name'])->value('id');
            $postData['sort_id'] = $existSortId ?? (new Sorts)->insertGetId(['name' => $postData['sort_name']]);
            unset($postData['sort_name']);
            if ($editId) {
                Articles::where('id', $editId)->update($postData);
            } else {
                $postData['created_ip'] = IpInfoUtils::info()['ip'];
                Articles::create($postData);
            }

            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }

        return $this->successMsg($editId ? '编辑成功' : '提交成功');
    }

    public function getArticle($id)
    {
        return $this->success(Articles::find($id)->append(['sort_name']));
    }

    public function delArticle($id)
    {
        Articles::find($id)->delete();
        return $this->successMsg('删除成功！');
    }
}
